package com.bilubi.reggie.reggie.controller;


import com.bilubi.reggie.reggie.bean.User;
import com.bilubi.reggie.reggie.common.R;
import com.bilubi.reggie.reggie.enums.CodeEnum;
import com.bilubi.reggie.reggie.service.UserService;
import com.bilubi.reggie.reggie.utils.VerificationCodeUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping(value = "/sendMsg", method = RequestMethod.POST)
    public R<String> generateValidateKeyCode(@RequestBody User user, HttpSession session){
        String code = VerificationCodeUtil.generateCode();
        log.info("code:{}", code);
        String phone = user.getPhone();
        if (phone != null && !phone.isEmpty()){
//            session.setAttribute(phone, code);
            redisTemplate.opsForValue().set(phone, code, 5L, TimeUnit.MINUTES);
        }
        return R.success();
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public R<User> login(@RequestBody Map<String,String> user, HttpSession session){
        log.info("user:{}", user);
        if (user.get("phone") == null){
            return R.error(CodeEnum.PHONE_ERROR);
        }
//        String code = (String) session.getAttribute(user.get("phone"));
        String code = (String) redisTemplate.opsForValue().get(user.get("phone"));
        if (!code.equals(user.get("code"))){
            return R.error(CodeEnum.CODE_ERROR);
        }
        User user_ = userService.getUserByPhone(user.get("phone"));
        session.setAttribute("user", user_);
        redisTemplate.delete(user.get("phone"));
        return R.success(user_);
    }

    @RequestMapping(value = "/loginout", method = RequestMethod.POST)
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success();
    }

}
